package com.server.modules.api.service.impl;

import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.*;
import com.pingplusplus.model.Identification;
import com.server.common.utils.PathUtils;
import com.server.modules.api.dao.MemberBankCardAPIDao;
import com.server.modules.api.service.IBankCarkService;
import com.server.modules.api.vo.BankCardInfoVo;
import com.server.modules.api.vo.BaseQueryVo;
import com.server.modules.sys.entity.bank.BankCardBin;
import com.server.modules.sys.entity.member.MemberBankcard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by Administrator on 2016/11/14.
 */
@Service
public class BankCardPingxxServiceImpl implements IBankCarkService {

    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private MemberBankCardAPIDao memberBankCardAPIDao;

    Properties properties = PathUtils.getProperties("application.properties");
    /**
     * 设置ping++key
     *
     * @return
     */
    private void setPingppKey() {
        String apiKeyTest= properties.getProperty("pingxx_apiKeyTest");
        String keyType = properties.getProperty("pingppKey");
        String apiKey= properties.getProperty("pingxx_apiKey");
        if ("liveKey".equals(keyType)) {
            // 生产key
            Pingpp.apiKey = apiKey;
        } else {
            // 其他情况都使用测试key
            Pingpp.apiKey = apiKeyTest;
        }
    /*   Pingpp.privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" +
                "MIICXAIBAAKBgQC4K7uQOSGWHr+lPEIzRCQu8RaToOmUbs7xFmxXBmkIVeFIi0Oe\n" +
                "zVypT968TqbSyZJNhduy4fiiI0Hj9d5eJyLOViGUxw266X/XlEaMjGcu0IrluAe2\n" +
                "oQF+WSUJLtk2cYmj+zP58KnrWCvs2gX4Kpw11/lMWsdNQQV/LhfG8B8E1QIDAQAB\n" +
                "AoGBAIgubka6uAcVPYilAh5+aHL9ekA3YACN3x+OARZoewna1vaZY6rtF3Nqx7xe\n" +
                "PCTpP/Fq5YVkakEZ6QLzLzZXoffFtY7M9GHDBkC7OWFjN+Mvld3sME9K+kpA/SiA\n" +
                "JAE5/6TuGUD1b7sUJMT7vqmzX7QWY/GKhWXx0QFc/BQKdfaRAkEA8xmsIElgoB5V\n" +
                "c+7CFbxKxjwX7tGOYClTJmXeHwpbfMIzNO8hHr3lUqT/5NUBqaO2AGWbQXrDiJID\n" +
                "FoDyJqeGUwJBAMHxjLgT1R+QGmMlv/VXEr3/tARCq1+1S97MDNZ6OBccsB2R6oNw\n" +
                "PITHGA/cOHwPmSVRLBwHzAMXO1ufcnkTEzcCQGJoyBch3S20Wd9ejc8CtDpfZUjW\n" +
                "KA6ha/mlTy+9n593dgc9rmilcsnr5XMbD1s+3JR4jUsKiVEl2n4noN8o/eUCQC9K\n" +
                "5KKai3TX4edddDKyWeqk6NPFIh8DiY25ukOup/DS2QtM4p/MhaVnGzH65Hc0Iocc\n" +
                "BSKMsC3sw1ezSOnHQf8CQC5h5jKoPiV4bndmoJgvgQiIvuLjAqMzzb260VSy7BR2\n" +
                "rc26WiCjTXj/gRL6JaZnjdXefeozMILtq6PfCVqtVUc=\n" +
                "-----END RSA PRIVATE KEY-----";*/


         Pingpp.privateKeyPath=BankCardPingxxServiceImpl.class.getClassLoader().getResource("rsa_private_key.pem").getPath();
    }
    /**
     * 认证银行卡信息
     *
     * 参考文档：https://www.pingxx.com/api#请求认证接口
     */
    @Override
    public BaseQueryVo identifyBankCard(BankCardInfoVo vo) {
        BaseQueryVo ret = new BaseQueryVo();
        ret.setRetCode(-1);
        ret.setRetMsg("未知错误");
        try {
            setPingppKey();
            String app_id= properties.getProperty("pingxx_appId");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("app", app_id);
            params.put("type", vo.getType()); // 身份证信息或者银行卡信息串，取值范围: "id_card"（身份证信息串）；"bank_card"（银行卡信息串）。
            Map<String, String> data = new HashMap<String, String>();
            data.put("id_name",vo.getData().getId_name());
            data.put("id_number", vo.getData().getId_number());
            data.put("card_number",vo.getData().getCard_number());
            data.put("phone_number",vo.getData().getPhone_number());
            params.put("data", data);
            Identification  result = Identification.identify(params);
            if (result.getResultCode() == 0) {
                ret.setRetCode(0);
                ret.setRetMsg("身份认证通过");
            } else {
                ret.setRetCode(result.getResultCode());
                ret.setRetMsg(result.getMessage());
            }
            logger.info("============================================");
             System.out.println(result);
            logger.info(result.toString());
            logger.info("============================================");
        } catch (InvalidRequestException e) {
            e.printStackTrace();
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIException e) {
            e.printStackTrace();
        } catch (ChannelException e) {
            e.printStackTrace();
        } catch (RateLimitException e) {
            e.printStackTrace();
        } catch (com.pingplusplus.exception.AuthenticationException e) {
            e.printStackTrace();
        }finally {
            return ret;
        }
    }

    @Override
    public MemberBankcard getBankcardByMemberId(String memberId) {
        return memberBankCardAPIDao.getBankcardByMemberId(memberId);
    }

    @Override
    public MemberBankcard getBankcardByCardNum(String cardNum) {
        return memberBankCardAPIDao.getBankcardByCardNum(cardNum);
    }

    @Override
    public BankCardBin getBankCardBinByCardNum(String cardNum) {
        return memberBankCardAPIDao.getBankCardBinByCardNum(cardNum);
    }
}
